package com.itlaobing.demo.servlet;

import com.itlaobing.demo.model.UserinfoModel;
import com.itlaobing.demo.service.UserinfoService;
import com.itlaobing.demo.service.impl.UserinfoServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname LoginServlet
 * @Description TODO()
 * @Date 2020/11/10 0010 11:22
 * @Author by Administrator
 * @Version v1.0
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserinfoService service = new UserinfoServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String captcha = req.getParameter("jcaptchaCode");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 校验验证码
        if (!CaptchaUtil.ver(captcha, req)){
            //清空验证码
            CaptchaUtil.clear(req);
            // 验证码错误
            req.setAttribute("msg", "验证码错误");
            // 返回到登录页面, 请求转发
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }
        CaptchaUtil.clear(req);

        // 验证码正确,做登录验证
        UserinfoModel model = service.login(username, password, req);
        if (model == null){
            // 请求转发，将请求转发到另外一个服务器资源中
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }else{
            // 重定向，是让客户端再发送一个请求
            resp.sendRedirect("page?action=index");
        }
    }
}
